import {Ajax} from '../ajax/index'

let $g = {};
let id = 10000;
const Global = {
    /**
     * 获取全局变量
     * @param {string} name
     */
    get(name) {
        if (typeof (name) === 'string' && name.length > 0) {
            return $g[name];
        } else {
            throw 'Global.set语法错误：name必须传入非空字符串'
        }
    },
    /**
     * 设置全局变量
     * @param {String}name
     * @param value
     */
    set(name, value) {
        if (typeof (name) === 'string' && name.length > 0) {
            $g[name] = value;
        } else {
            throw 'Global.set语法错误：name必须传入非空字符串'
        }
    },
    /**
     * 移除全局变量
     * @param {string} name
     */
    remove(name) {
        if (typeof (name) === 'string' && name.length > 0) {
            delete $g[name];
        } else {
            throw 'Global.remove语法错误：name必须传入非空字符串'
        }
    },

    newId() {
        id++;
        return id;
    },
    /**
     * 数据缓存
     * @param {string}name - 缓存的变量名
     * @param {string}api - 接口地址
     * @param {Object}paras - 参数
     * @param {function}filter - 处理函数，可不传
     * @returns {*}
     */
    dataCache(name, api, paras = {}, filter) {
        if (Global.get(name)) {
            return new Promise(function (resolve) {
                resolve($g[name]);
            })
        } else {
            return Ajax.get(api, paras).then(data => {
                const result = filter ? filter(data) : data;
                $g[name] = result;
                return result;
            });
        }
    }
};

export {
    Global
}

export default Global;
